package redissession

import (
	"bytes"
	"crypto/rand"
	"encoding/base64"
	"encoding/gob"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/gomodule/redigo/redis"
)

var MaxPoolSize = 100

// var RedisHost = "127.0.0.1"
type sessionmap map[interface{}]interface{}

//底层数据操作
type Session interface {
	Set(key string, value interface{})
	Get(key string) interface{}
	Remove(key string) error
	GetId() string
}

type SessionStore struct {
	sid  string
	lock sync.RWMutex
	// maxlifetime int64
	data sessionmap
}

func newSessionRedis() *SessionStore {
	return &SessionStore{
		// maxlifetime: 60 * 30,
		data: make(map[interface{}]interface{}),
	}
}

func (rs *SessionStore) Set(key string, value interface{}) {
	rs.lock.Lock()
	defer rs.lock.Unlock()
	rs.data[key] = value
}

func (rs *SessionStore) Get(key string) interface{} {
	rs.lock.RLock()
	defer rs.lock.RUnlock()

	if v, ok := rs.data[key]; ok {
		return v
	}
	return nil
}

func (rs *SessionStore) Remove(key string) error {
	if _, ok := rs.data[key]; ok {
		delete(rs.data, key)
	}
	return nil
}

func (rs *SessionStore) GetId() string {
	return rs.sid
}

type Provider struct {
	maxlifetime int64
	savePath    string
	poolsize    int
	host        string
	password    string
	dbNum       int
	store       *SessionStore
	poollist    *redis.Pool
}

func newProvider() *Provider {
	return &Provider{store: newSessionRedis()}
}

//"host,maxpoolsize,password,dbnum"
//初始化redis
func (rp *Provider) SessionInit(maxlifetime int64, savePath string) error {
	rp.maxlifetime = maxlifetime

	configs := strings.Split(savePath, ",")

	if len(configs) > 1 {
		poolsize, err := strconv.Atoi(configs[1])
		rp.host = configs[0]
		if err != nil || poolsize < 0 {
			rp.poolsize = MaxPoolSize
		} else {
			rp.poolsize = poolsize
		}
	} else {
		rp.host = configs[0]
		rp.poolsize = MaxPoolSize
	}
	if len(configs) > 2 {
		rp.password = configs[2]
	}
	if len(configs) > 3 {
		dbnum, err := strconv.Atoi(configs[3])
		if err != nil || dbnum < 0 {
			rp.dbNum = 0
		} else {
			rp.dbNum = dbnum
		}
	} else {
		rp.dbNum = 0
	}
	fmt.Println(rp.dbNum, rp.password, rp.poolsize, rp.host)

	rp.poollist = redis.NewPool(func() (redis.Conn, error) {
		c, err := redis.Dial("tcp", rp.host)
		if err != nil {
			return nil, err
		}
		if rp.password != "" {
			if _, err = c.Do("AUTH", rp.password); err != nil {
				c.Close()
				return nil, err
			}
		}
		//some redis proxy such as twemproxy is not support select command
		if rp.dbNum > 0 {
			_, err = c.Do("SELECT", rp.dbNum)
			if err != nil {
				c.Close()
				return nil, err
			}
		}
		return c, err
	}, rp.poolsize)

	return rp.poollist.Get().Err()
}

//获取SessionStore
func (rp *Provider) SessionRead(sid string) (*SessionStore, error) {
	c := rp.poollist.Get()
	defer c.Close()

	var kv map[interface{}]interface{}
	kvs, err := redis.String(c.Do("GET", sid))
	if err != nil && err != redis.ErrNil {
		return nil, err
	}
	if len(kvs) == 0 {
		kv = make(map[interface{}]interface{})
	} else {
		if kv, err = DecodeGob([]byte(kvs)); err != nil {
			return nil, err
		}
	}
	r_data := &SessionStore{sid: sid, data: kv}
	return r_data, nil
}

//session写入
func (rp *Provider) SessionRelease(sid string, sdata sessionmap) error {
	b, err := EncodeGob(sdata)
	if err != nil {
		return err
	}
	c := rp.poollist.Get()
	defer c.Close()
	c.Do("SETEX", sid, rp.maxlifetime, string(b))
	return nil
}

//session更新
func (rp *Provider) SessionUpdate(sid string) error {
	c := rp.poollist.Get()
	defer c.Close()

	existed, err := redis.Int(c.Do("EXPIRE", sid, rp.maxlifetime))
	fmt.Println(existed, "####")
	if err != nil || existed == 0 {
		return fmt.Errorf("%s存活时间修改失败", sid)
	}
	return nil

}

//判断session是否存在
func (rp *Provider) SessionExit(sid string) bool {
	c := rp.poollist.Get()
	defer c.Close()
	existed, err := redis.Int(c.Do("EXISTS", sid))
	if err != nil || existed == 0 {
		return false // sid不存在
	}
	// if existed, err := redis.Int(c.Do("EXISTS", sid)); err != nil || existed != 0 {
	// 	return false // sid不存在
	// }
	return true // sid存在
}

//删除session
func (rp *Provider) SessionDestroy(sid string) error {
	c := rp.poollist.Get()
	defer c.Close()

	c.Do("DEL", sid)
	return nil
}

type SessionManager struct {
	cookieName  string
	nprovider   *Provider
	maxlifetime int64
	lock        sync.Mutex
}

// 初始化SessionManager
func NewSessionManager(mtime int64, spath string) (*SessionManager, error) {
	SessionManager := &SessionManager{
		cookieName:  "lzy-cookie",
		nprovider:   newProvider(),
		maxlifetime: mtime,
	}
	err := SessionManager.nprovider.SessionInit(mtime, spath)
	if err != nil {
		return nil, err
	}
	return SessionManager, nil
}

// 获取默认的cookie name
func (rm *SessionManager) GetCookieN() string {
	return rm.cookieName
}

// 判断cookie以及redis session缓存是否存在
func (rm *SessionManager) CookieIsExists(r *http.Request) bool {
	cookie, err := r.Cookie(rm.cookieName)
	if err != nil || cookie.Value == "" {
		return false //cookie不存在
	} else {
		sid, _ := url.QueryUnescape(cookie.Value)
		if rm.nprovider.SessionExit(sid) {
			return true //cookie存在
		} else {
			return false
		}
		return true

	}
}

// 判断redis 缓存是否存在
func (rm *SessionManager) SessionIsExists(sid string) bool {
	if rm.nprovider.SessionExit(sid) {
		return true //cookie存在
	} else {
		return false
	}
}

// 获取 sid
func (rm *SessionManager) GetSid(w http.ResponseWriter, r *http.Request) (string, error) {
	cookie, err := r.Cookie(rm.cookieName)
	if err != nil {
		return "", err
	}

	sid, err := url.QueryUnescape(cookie.Value)
	if err != nil {
		return "", err
	}

	return sid, nil
}

// 获取Session结构体
func (rm *SessionManager) GetSession() *SessionStore {
	nsession := newSessionRedis()
	return nsession
}

// 获取指定sid 的 Session结构体
func (rm *SessionManager) GetSessionById(sid string) (*SessionStore, error) {
	r_data, err := rm.nprovider.SessionRead(sid)
	if err != nil {
		return nil, err
	}
	return r_data, nil
}

// 生成cookie和session
func (rm *SessionManager) BeginCookie(w http.ResponseWriter, r *http.Request, sdata *SessionStore) error {
	rm.lock.Lock()
	defer rm.lock.Unlock()

	sid := rm.randomId()
	fmt.Println("生成ID")
	for {
		if rm.nprovider.SessionExit(sid) {
			fmt.Println("sid已经存在")
			sid = rm.randomId()
		} else {
			fmt.Println("sid不存在")
			break
		}
	}
	maxAge := rm.maxlifetime
	err := rm.nprovider.SessionRelease(sid, sdata.data)
	if err != nil {
		return err
	}
	cookie := http.Cookie{
		Name:     rm.cookieName,
		Value:    url.QueryEscape(sid),
		Path:     "/",
		HttpOnly: true,
		MaxAge:   int(maxAge),
		Expires:  time.Now().Add(time.Duration(maxAge)),
	}
	http.SetCookie(w, &cookie)

	return nil
}

//更新
func (rm *SessionManager) Update(w http.ResponseWriter, r *http.Request) error {
	cookie, err := r.Cookie(rm.cookieName)
	if err != nil {
		return err
	}
	sid, _ := url.QueryUnescape(cookie.Value)
	err = rm.nprovider.SessionUpdate(sid)
	if err != nil {
		return err
	}
	cookie.MaxAge = int(rm.maxlifetime)
	http.SetCookie(w, cookie)
	return nil
}

//删除cookies
func (rm *SessionManager) Destroy(w http.ResponseWriter, r *http.Request) error {
	cookie, err := r.Cookie(rm.cookieName)
	if err != nil {
		return err
	}

	sid, err := url.QueryUnescape(cookie.Value)
	if err != nil {
		return err
	}

	//删除session
	rm.nprovider.SessionDestroy(sid)
	decookie := http.Cookie{
		MaxAge:  0,
		Name:    rm.cookieName,
		Value:   "",
		Path:    "/",
		Expires: time.Now().Add(time.Duration(0)),
	}
	http.SetCookie(w, &decookie)
	return nil
}

//判断cookie和session是否存在，否则跳转到指定页面
func (rm *SessionManager) SessionJudge(urls string, w http.ResponseWriter, r *http.Request) bool {
	cookie, err := r.Cookie(rm.cookieName)
	if err != nil {
		http.Redirect(w, r, urls, http.StatusFound)
		return true
	}
	sid, err := url.QueryUnescape(cookie.Value)
	if err != nil {
		http.Redirect(w, r, urls, http.StatusFound)
		return true
	}

	if rm.nprovider.SessionExit(sid) {
		return false
	} else {
		http.Redirect(w, r, urls, http.StatusFound)
		return true
		// , fmt.Errorf("session不存在")
	}
}

//生成随机sid
func (rm *SessionManager) randomId() string {
	b := make([]byte, 32)
	if _, err := io.ReadFull(rand.Reader, b); err != nil {
		return ""
	}
	//加密
	return base64.URLEncoding.EncodeToString(b)
}

//编码
func EncodeGob(obj sessionmap) ([]byte, error) {
	for _, v := range obj {
		gob.Register(v)
	}
	buf := bytes.NewBuffer(nil)
	enc := gob.NewEncoder(buf)
	err := enc.Encode(obj)
	if err != nil {
		return []byte(""), err
	}
	return buf.Bytes(), nil
}

func DecodeGob(encoded []byte) (sessionmap, error) {
	buf := bytes.NewBuffer(encoded)
	dec := gob.NewDecoder(buf)
	var out map[interface{}]interface{}
	err := dec.Decode(&out)
	if err != nil {
		return nil, err
	}
	return out, nil
}
